package nl.han.ica.ap.searchengine.server;

import java.util.List;

import nl.han.ica.ap.searchengine.server.crawling.SourceFileException;
import nl.han.ica.ap.searchengine.server.crawling.WebpageIndexer;
import nl.han.ica.ap.searchengine.server.pagerank.PagerankCalculator;
import nl.han.ica.ap.searchengine.shared.database.DatabaseConnectionException;
import nl.han.ica.ap.searchengine.shared.database.DatabaseQueryException;
import nl.han.ica.ap.searchengine.shared.database.SearchEngineDatabase;
import nl.han.ica.ap.searchengine.shared.sdo.Webpage;

public class SearchEngineServer {
	
	private static final String URL_FILE_LOCATION = "/urllist.txt";
	private static List<Webpage> index;
	
	public static final void main(final String[] args) {
		write(MessageType.INFO, "SearchEngine Server started.");
		
		startServer();
			
		write(MessageType.INFO, "Shutting down...");
	}

	private static void startServer() {
		try {
			indexWebpages();
			calculatePagerank();
			storeResults();
		} catch (SourceFileException e) {
			write(MessageType.ERROR, "An IO error occured while trying to read the sourcefile into memory.");
		} catch (DatabaseConnectionException e) {
			write(MessageType.ERROR, "An error occured while connecting to the database.");
		} catch (DatabaseQueryException e) {
			write(MessageType.ERROR, "An error occured while communicating with the database.");
		}
	}

	private static void indexWebpages() throws SourceFileException {
		write(MessageType.INFO, "Indexing webpages...");
		WebpageIndexer wi = new WebpageIndexer(URL_FILE_LOCATION);
		index = wi.startIndexing();
		write(MessageType.INFO, "Indexing complete!");
	}

	private static void calculatePagerank() {
		write(MessageType.INFO, "Calculating PageRank values...");
		PagerankCalculator pc = new PagerankCalculator(index);
		index = pc.calculatePagerank();
		write(MessageType.INFO, "PageRank calculations complete!");
	}

	private static void storeResults() throws DatabaseConnectionException, DatabaseQueryException {
		write(MessageType.INFO, "Storing webpages to database...");
		SearchEngineDatabase sed = new SearchEngineDatabase();
		sed.batchInsert(index);
		write(MessageType.INFO, "Webpages stored!");
	}
	
	private static final void write(final MessageType type, final String message) {
		System.out.println(type + " " + message);
	}
	
	private enum MessageType {
		
		INFO("INFO"),
		ERROR("ERROR");
		
		private String text;
		
		private MessageType(final String text) {
			this.text = text;
		}
		
		@Override
		public final String toString() {
			return "[" + this.text + "]";
		}
		
	}
	
}
